﻿YAHOO.example.init = function () {
    function onButtonClick(p_oEvent) {
        switch (this.get("id")) {
            case "btnSave":
                Save(flag);
                break;
            case "btnClose":
                Close();
                break;
            default:
                break;
        }
    }
    YAHOO.util.Event.onContentReady("toolbar", function () {
        btnSave = new YAHOO.widget.Button("btnSave");
        btnSave.on("click", onButtonClick);
        btnClose = new YAHOO.widget.Button("btnClose");
        btnClose.on("click", onButtonClick);
        if (flag == "5") {  //查看
            btnSave._button.style.display = "none";
            $("#btnSave").attr('disabled', "true");
        }
    });
} ();
//客户选择对应的方法和ID
var _fn, _id;
function ShowDialog(fn, id, src) {
    _fn = fn;
    _id = id;
    document.getElementById("EditUIWindow1").src = src;
    YAHOO.example.container.dialog1.show();
}
//业绩归属选择对应的方法和ID
var _fn, _id;
function ShowDialog2(fn, id) {
    _fn = fn;
    _id = id;
    YAHOO.example.container.dialog2.show();
}

function GetState(flags) {
    $('#btnCustomerCode').css("display", "none");
    $('#btnTeacherId').css("display", "none");
    $('#PaymentId').attr("disabled", "true");
    $('#PillID').attr("disabled", "true");
    $('#ValutaID').attr("disabled", "true");
    var obj = document.getElementById("fieldForm"); //得到DIV对象
    var e = obj.getElementsByTagName("input"); //得到此DIV里的所有INPUT对象
    var t = obj.getElementsByTagName("textarea");
    if (flag == "0") { //0:新增 
        $('#StateID').attr("disabled", "true");
        $('#PaymentId').removeAttr("disabled", "");
        $('#PillID').removeAttr("disabled", "");
        $('#ValutaID').removeAttr("disabled", "");
        $('#btnCustomerCode').css("display", "");
        $('#btnTeacherId').css("display", "");
    }
    if (flag == "1") { //1:新建状态 变更 只改状态 
        $('#btnDeptId').css("display", "none");
        $('#drpTeacherType').attr("disabled", "true");
        for (var i = 0; i < e.length; i++) {
            if (e[i].id == "txtTeacherTime") {
                e[i].disabled = true;
            } else {
                $("#" + e[i].id + "").attr("readonly", "readonly");
            }
        }
        for (var k = 0; k < t.length; k++) {
            $("#" + t[k].id + "").attr("readonly", "readonly");
        }
    }
    if (flag == "2") { //2:其它状态变更
        if (uname != "admin") {
            $("#StateID>option:eq(0)").remove(); //去掉新建订单状态
            $("#StateID>option:eq(3)").remove(); //去掉结案订单状态
        } else {
            $('#btnCustomerCode').css("display", "none");
        }
        for (var i = 0; i < e.length; i++) {
            if (e[i].id == "txtTeacherTime" || e[i].id == "txtTeacherAddress") {
                $("#" + e[i].id + "").removeAttr("readonly");
            } else {
                $("#" + e[i].id + "").attr("readonly", "readonly");
            }
        }
        for (var k = 0; k < t.length; k++) {
            $("#" + t[k].id + "").attr("readonly", "readonly");
        }
    }
    if (flag == "4") { //允许修改所有信息
        $('#btnCustomerCode').css("display", "none");
        $('#PaymentId').removeAttr("disabled", "");
        $('#PillID').removeAttr("disabled", "");
        $('#ValutaID').removeAttr("disabled", "");
        $('#btnTeacherId').css("display", "");
    }
    if (flag == "5") { //查看
        $('#StateID').attr("disabled", "true");
        $('#drpTeacherType').attr("disabled", "true");
        $('#btnDeptId').css("display", "none");
        for (var i = 0; i < e.length; i++) {
            if (e[i].id == "txtTeacherTime") {
                e[i].disabled = true;
            } else {
                $("#" + e[i].id + "").attr("readonly", "readonly");
            }
        }
        for (var k = 0; k < t.length; k++) {
            $("#" + t[k].id + "").attr("readonly", "readonly");
        }
    }
}

//选择客户编码显示客户信息
var LoadCustomerData = function () {
    var vCId = "ID='" + $("#CustomerCode").val() + "'";
    YAHOO.util.Connect.asyncRequest('GET', "../../Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=V_CrmCustomer&customCondition=" + vCId + "", //条件 
        {success: function (res) {
            try {
                var str = res.responseText;
                var arr = [];
                var obj = eval(str);
                $("#txtCustomerCodes").val(obj[0].Code);
                $("#CustomerName").val(obj[0].CustomerName);
                $("#CustomerType").val(obj[0].CustomerType);
                $("#PersonId").val(obj[0].PersonCount);
                $("#TradeId").val(obj[0].CustomerTrade);
                $("#CreateDate").val(obj[0].CompanyCreateDate);
                $("#CompanyProduct").val(obj[0].CompanyProduct);
                $("#SaleadName").val(obj[0].SaleadName);
                $("#AddUserName").val(obj[0].UName);
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
    });
}
//选择客户编码加载显示讲师行程
var LoadTeacherData = function () {
    var vCId = "CusID='" + $("#CustomerCode").val() + "'";
    YAHOO.util.Connect.asyncRequest('GET', "../../Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=V_CrmTeachHodometer&customCondition=" + vCId + "", //条件 
        {success: function (res) {
            try {
                var str = res.responseText;
                var arr = [];
                var obj = eval(str);
                if (str != "" && obj[0].N != "null") {
                    $("#TeacherId").val(obj[0].TeachID);
                    $("#txtTeacherId").val(obj[0].teachname);
                    $("#txtTeacherTime").val(obj[0].HmDate);
                    $("#txtTeacherAddress").val(obj[0].EXP1);
                    if (obj[0].Expr1 == "A") {
                        $("#drpTeacherType").get(0).selectedIndex = 1;
                    } else if (obj[0].Expr1 == "P") {
                        $("#drpTeacherType").get(0).selectedIndex = 2;
                    } else if (obj[0].Expr1 == "N") {
                        $("#drpTeacherType").get(0).selectedIndex = 3;
                    }
                } else {
                    $("#TeacherId").val("");
                    $("#txtTeacherId").val("");
                    $("#txtTeacherTime").val("");
                    $("#txtTeacherAddress").val("");
                    $("#drpTeacherType").get(0).selectedIndex = 0;
                }
            }
            catch (e) {
                $("#TeacherId").val("");
                $("#txtTeacherId").val("");
                $("#txtTeacherTime").val("");
                $("#txtTeacherAddress").val("");
                $("#drpTeacherType").get(0).selectedIndex = 0;
            }
            finally {
            }
        }, failure: function () { }
    });
}
YAHOO.namespace("example.container");
YAHOO.util.Event.onDOMReady(function () {
    var handleSubmit = function () {
        var editwindow = document.getElementById("EditUIWindow1");
        if (editwindow) {
            editwindow.contentWindow.ChooseInfo();
            if (_id == "btnCustomerCode") {
                LoadCustomerData();
                LoadTeacherData();
            }
        }
        YAHOO.example.container.dialog1.hide();
    };
    var handleSubmit2 = function () {
        var editwindow = document.getElementById("EditUIWindow2");
        if (editwindow) {
            editwindow.contentWindow.ChooseInfo();
        }
        YAHOO.example.container.dialog2.hide();
    };
    var handleCancel = function () {
        this.cancel();
    };
    var handleSuccess = function (o) {
        var response = o.responseText;
        response = response.split("<!")[0];
        document.getElementById("resp").innerHTML = response;
    };
    var handleFailure = function (o) {
        alert("Submission failed: " + o.status);
    };
    YAHOO.example.container.dialog1 = new YAHOO.widget.Dialog("dialog1",
					            { width: "650px",
					                height: "400px",
					                fixedcenter: true,
					                visible: false,
					                draggable: true,
					                close: true,
					                modal: true,
					                autofillheight: "body",
					                constraintoviewport: true,
					                buttons: [{ text: "确定", handler: handleSubmit, isDefault: true },
								            { text: "取消", handler: handleCancel}]
					            });
    YAHOO.example.container.dialog2 = new YAHOO.widget.Dialog("dialog2",
					            { width: "300px",
					                height: "400px",
					                fixedcenter: true,
					                visible: false,
					                draggable: true,
					                close: true,
					                modal: true,
					                autofillheight: "body",
					                constraintoviewport: true,
					                buttons: [{ text: "确定", handler: handleSubmit2, isDefault: true },
								            { text: "取消", handler: handleCancel}]
					            });
    YAHOO.example.container.dialog1.callback = { success: handleSuccess, failure: handleFailure };
    YAHOO.example.container.dialog1.render();
    YAHOO.example.container.dialog2.callback = { success: handleSuccess, failure: handleFailure };
    YAHOO.example.container.dialog2.render();
    //拖动大小1
    var resize = new YAHOO.util.Resize("dialog1", {
        handles: ["br"],
        autoRatio: false,
        minWidth: 450,
        minHeight: 300,
        status: false
    });
    resize.on("startResize", function (args) {
        if (this.cfg.getProperty("constraintoviewport")) {
            var D = YAHOO.util.Dom;

            var clientRegion = D.getClientRegion();
            var elRegion = D.getRegion(this.element);

            resize.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
            resize.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
        } else {
            resize.set("maxWidth", null);
            resize.set("maxHeight", null);
        }

    }, YAHOO.example.container.dialog1, true);
    resize.on("resize", function (args) {
        var panelHeight = args.height;
        this.cfg.setProperty("height", panelHeight + "px");
    }, YAHOO.example.container.dialog1, true);
    //拖动大小2
    var resize = new YAHOO.util.Resize("dialog2", {
        handles: ["br"],
        autoRatio: false,
        minWidth: 300,
        minHeight: 250,
        status: false
    });
    resize.on("startResize", function (args) {
        if (this.cfg.getProperty("constraintoviewport")) {
            var D = YAHOO.util.Dom;

            var clientRegion = D.getClientRegion();
            var elRegion = D.getRegion(this.element);

            resize.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
            resize.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
        } else {
            resize.set("maxWidth", null);
            resize.set("maxHeight", null);
        }

    }, YAHOO.example.container.dialog2, true);
    resize.on("resize", function (args) {
        var panelHeight = args.height;
        this.cfg.setProperty("height", panelHeight + "px");
    }, YAHOO.example.container.dialog2, true);
});
//刷新父窗体数据
function RefreshDataParent() {
    if (parent.NeedRefreshPage != null) {
        if (typeof (parent.NeedRefreshPage.LoadData) == "function") {
            parent.NeedRefreshPage.RefreshData();
        }
    }
}

//取值
function setValue() {
    instance[0].ID = $('#ID').val();
    instance[0].Code = $('#Code').val();
    instance[0].CustomerId = $('#CustomerCode').val();
    instance[0].DeptId = $('#DeptId').val();
    instance[0].Date = $('#Date').val();
    instance[0].TypeID = $('#TypeID').val();
    instance[0].ValutaID = $('#ValutaID').val();
    instance[0].PillID = $('#PillID').val();
    instance[0].PaymentId = $('#PaymentId').val();
    instance[0].StateID = $('#StateID').val();
    instance[0].Explain = $('#Explain').val().replace(/(^\s*)|(\s*$)/g, '');
    instance[0].TotalMoney = $('#TotalMoney').val();
    instance[0].CheckUser = "00000000-0000-0000-0000-000000000000";
    //讲师约场信息
    instance[0].TeacherId = $("#TeacherId").val();
    instance[0].TeacherTime = $("#txtTeacherTime").val();
    instance[0].TeacherAddress = $("#txtTeacherAddress").val();
    instance[0].TeacherType = $("#drpTeacherType").val();
}
//保存
var Save = function (obj) {
    if (flag == "0" || flag == "2" || flag == "4") {  //0新增  2新建变更 4可以修改所有信息
        setValue();
        if (instance[0].Code == "" || instance[0].Code == null) {
            alert("订单编码不能为空!");
            $('#Code').focus();
            return;
        }
        if (instance[0].CustomerId == "" || instance[0].CustomerId == null) {
            alert("客户名称不能为空!");
            $('#CustomerName').focus();
            return;
        }
        if (instance[0].Date == "" || instance[0].Date == null) {
            alert("订单日期不能为空!请填写您实际成交日期!");
            $('#Date').focus();
            return;
        }
        if (instance[0].CourseLoyoutID == "" || instance[0].CourseLoyoutID == null) {
            instance[0].CourseLoyoutID = "00000000-0000-0000-0000-000000000000";
            //alert("订单期数不能为空!");
            //$('#CourseLoyoutID').focus();
            //return;
        }
        if (instance[0].TypeID == "" || instance[0].TypeID == null) {
            alert("订单类型不能为空!");
            $('#TypeID').focus();
            return;
        }
        if (instance[0].ValutaID == "" || instance[0].ValutaID == null) {
            instance[0].ValutaID = "00000000-0000-0000-0000-000000000000";
            //alert("币别不能为空!");
            //$('#ValutaID').focus();
            //return;
        }
        if (instance[0].PillID == "" || instance[0].PillID == null) {
            instance[0].PillID = "00000000-0000-0000-0000-000000000000";
            //alert("汇率不能为空!");
            //$('#PillID').focus();
            //return;
        }
        if (instance[0].DeptId == "" || instance[0].DeptId == null) {
            alert("业绩归属不能为空!");
            $('#txtDeptId').focus();
            return;
        }
        if (instance[0].PaymentId == "" || instance[0].PaymentId == null) {
            alert("付款方式不能为空!");
            $('#PaymentId').focus();
            return;
        }
        if (instance[0].StateID == "" || instance[0].StateID == null) {
            alert("订单状态不能为空!");
            $('#StateID').focus();
            return;
        }
        if (instance[0].TotalMoney == "" || instance[0].TotalMoney == null) {
            alert("场次费不能为空!");
            $('#TotalMoney').focus();
            return;
        }
        if (instance[0].TeacherId == "" || instance[0].TeacherId == null) {
            alert("推广讲师不能为空!");
            $('#txtTeacherId').focus();
            return;
        }
        if (instance[0].TeacherTime == "" || instance[0].TeacherTime == null) {
            alert("讲场时间不能为空!");
            $('#txtTeacherTime').focus();
            return;
        }
        if (instance[0].TeacherAddress == "" || instance[0].TeacherAddress == null) {
            alert("讲场地点不能为空!");
            $('#txtTeacherAddress').focus();
            return;
        }
        if (instance[0].TeacherType == "" || instance[0].TeacherType == null) {
            alert("讲场类型不能为空!");
            $('#drpTeacherType').focus();
            return;
        }
        if (flag == "2" || flag == "4") {
            if (confirm("您确定修改当前订单信息吗?")) {
                var json = $.toJSON(instance[0]).replace(/'/g, "[B]");
                $("#jsonDataContent").val(json);
                trySave(obj);
            }
        } else {
            if (confirm("您确定保存当前订单信息吗?")) {
                var json = $.toJSON(instance[0]).replace(/'/g, "[B]");
                $("#jsonDataContent").val(json);
                trySave(obj);
            }
        }
    } else if (flag == "1") {  //变更状态
        if (confirm("您确定变更当前订单状态吗?")) {
            var vName = $("#StateID").find("option:selected").text();
            var CustomerId = $('#CustomerCode').val();
            var OrderId = $('#ID').val();
            var OrderStateId = $("#StateID").val();
            if (CustomerId == "") {
                alert("客户ID为空!保存失败!");
                return;
            }
            if (OrderId == "") {
                alert("订单ID为空!保存失败!");
                return;
            }
            if (vName == "") {
                alert("订单状态不能为空!");
                return;
            }
            if (OrderStateId == "" || OrderStateId == "") {
                alert("订单状态不能为空!");
                return;
            }
            var SaveUrl = Url + "?oid=" + OrderId + "&cid=" + CustomerId + "&sid=" + OrderStateId + "&name=" + encodeURI(vName) + "&action=" + action + "&entity=CrmCustomerOrderField";
            YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
                success: function (res) {
                    try {
                        var str = res.responseText;
                        if (str == "1") {
                            if (obj == 2) {
                                alert("数据保存成功!跳转到缴款单页面!");
                                var title = "新增缴款单信息";
                                window.parent.$("#tabs").tabs('close', title);
                                parent.addTabs(title, '../Crm/Modules/AddPay.aspx?OrderId=' + $('#ID').val() + '&flag=2&entity=CrmPay&title=' + encodeURI(title) + '');
                            } else {
                                alert("数据保存成功");
                            }
                            RefreshDataParent();
                            Close();
                        }
                        else {
                            alert(str);
                        }
                    }
                    catch (e) {
                    }
                    finally {
                    }
                },
                failure: function (error) {
                    alert("数据错误：" + error.statusText);
                }
            }, null);
        }
    }
}
var trySave = function (obj) {
    var formObject = document.getElementById('form2');
    YAHOO.util.Connect.setForm(formObject);
    if (obj == 0) {  //新建约场订单变更保存不跳转
        var cObj = YAHOO.util.Connect.asyncRequest('POST', Url + "?flag=1&action=" + action + "&entity=CrmCustomerOrderField", callback);
    } else if (obj == 1) { //约场订单变更保存跳转至缴款单页面
        var cObj = YAHOO.util.Connect.asyncRequest('POST', Url + "?flag=1&action=" + action + "&entity=CrmCustomerOrderField", callback1);
    } else if (obj == 2 || obj == 4) { //订单在新建状态下变更不跳转|//允许修改所有信息
        var cObj = YAHOO.util.Connect.asyncRequest('POST', Url + "?flag=1&action=" + action + "&entity=CrmCustomerOrderF", callback);
    } else if (obj == 3) { //订单在新建状态下变更跳转至缴款单页面
        var cObj = YAHOO.util.Connect.asyncRequest('POST', Url + "?flag=1&action=" + action + "&entity=CrmCustomerOrderF", callback1);
    }
}
var responseSuccess = function (res) {
    try {
        var str = res.responseText;
        if (str == "1") {
            alert("数据保存成功");
            RefreshDataParent(); //刷新父页面
            Close(); //关闭当前页
        } else if (str == "2") {
            alert("该讲师在当前时间段已安排讲场!");
            return;
        }
        else {
            alert(str);
            return;
        }
    } catch (e) {
    }
    finally {
    }
};
var responseSuccess1 = function (res) {
    try {
        var str = res.responseText;
        if (str == "1") {
            alert("数据保存成功!跳转到缴款单页面!");
            var title = "新增缴款单信息";
            window.parent.$("#tabs").tabs('close', title);
            parent.addTabs(title, '../Crm/Modules/AddPay.aspx?OrderId=' + $('#ID').val() + '&flag=2&entity=CrmPay&title=' + encodeURI(title) + '');
            RefreshDataParent();
            Close();
        }
        else {
            alert(str);
        }
    } catch (e) {
    }
    finally {
    }
}
var responseFailure = function (error) {
    alert("数据错误：" + error.statusText);
}
var callback = {
    success: responseSuccess,
    failure: responseFailure
};
var callback1 = {
    success: responseSuccess1,
    failure: responseFailure
};